package com.ittest;

import com.itzyf.dao.UserDao;
import com.itzyf.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Demo {

    @Test
    public void findAll() throws IOException {
        //查询全部
        InputStream is = Resources.getResourceAsStream("SqlMapConflg.xml");
        SqlSessionFactoryBuilder factory = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = factory.build(is);
        SqlSession session = build.openSession();
        UserDao mapper = session.getMapper(UserDao.class);

        List<User> users = mapper.findAll();
        for (User user : users) {
            System.out.println("user = " + user);
        }
    }
    @Test
    public void save() throws IOException {
        //添加
        InputStream is = Resources.getResourceAsStream("SqlMapConflg.xml");
        SqlSessionFactoryBuilder factory = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = factory.build(is);
        SqlSession session = build.openSession();
        UserDao mapper = session.getMapper(UserDao.class);

        User user = new User();
        user.setUsername("tom");
        user.setEmail("987654321@qq.com");
        user.setPassword("666");
        user.setPhoneNum("132444444444");

        mapper.save(user);

        session.commit();
    }

    @Test
    public void update()throws IOException{
        InputStream is = Resources.getResourceAsStream("SqlMapConflg.xml");
        SqlSessionFactoryBuilder factory = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = factory.build(is);
        SqlSession session = build.openSession();
        UserDao mapper = session.getMapper(UserDao.class);

        User user = new User();
        user.setId(3L);
        user.setUsername("liuxian");
        mapper.update(user);
        session.commit();
    }

    @Test
   public void delete()throws IOException{
        InputStream is = Resources.getResourceAsStream("SqlMapConflg.xml");
        SqlSessionFactoryBuilder factory = new SqlSessionFactoryBuilder();
        SqlSessionFactory build = factory.build(is);
        SqlSession session = build.openSession();
        UserDao mapper = session.getMapper(UserDao.class);

        mapper.delete(6);
        session.commit();
   }

}
